今天來用kotlin實作一個BaseActivity,方便以後跳頁傳值使用
fun start(next: Class<*>, bundle: Bundle?, finished: Boolean) {
val intent = Intent(this , next::class.java)
if(bundle == null)intent.putExtras(Bundle())
else intent.putExtras(bundle)
startActivity(intent)
if (finished) this.finish()
}
也可以用類似java的寫法
lateinit var intent : Intent
intent.setClass(this, next::class.java)
然後要記得用Bundle的空值設定,否則傳進去是空值的話會報錯
然後因為平常不會每一次都要傳值或是終止activity,所以可以在下面這麼做
fun start(next: Class<*>){
this.start(next,null,false)
}
fun start(next: Class<*>,bundle: Bundle?){
this.start(next,bundle,false)
}
fun start(next: Class<*>, finished: Boolean){
this.start(next,null,finished)
}
完整程式碼
class BaseActiivity : AppCompatActivity() {
fun start(next: Class<*>, bundle: Bundle?, finished: Boolean) {
lateinit var intent : Intent
intent.setClass(this, next::class.java)
if(bundle == null)intent.putExtras(Bundle())
else intent.putExtras(bundle)
startActivity(intent)
if (finished) this.finish()
}
fun start(next: Class<*>){
this.start(next,null,false)
}
fun start(next: Class<*>,bundle: Bundle?){
this.start(next,bundle,false)
}
fun start(next: Class<*>, finished: Boolean){
this.start(next,null,finished)
}
}